package com.eagle.security.handler;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;


public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements InitializingBean
{
    static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}

    // 用户日志
//    @Autowired(required = false)
//    protected UserLogManager userLogManager;
//
//    @Autowired(required = false)
//    private ApplicationContext context;
//
//    // 额外用户登录验证
//    private List<LoginExtraValidate> loginExtraValidates;
//
//    // 用户过期验证
//    private LoginExtraValidate overdueLoginExtraValidate = new OverdueLoginExtraValidate();
//
//    // 在线用户管理
//    @Autowired
//    private SessionRegistryImpl sessionRegistry;
//
//    // 权限属性常量类
//    @Autowired
//    private RoleBaseConstant rolesConstant;
//
//    private FieldMethodizer rolesConstantField;
//
//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException
//    {
//        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//        User user = (User) auth.getPrincipal();
//        user.setIp(IpUtils.getRemoteIpAddr(request));
//        user.setClientInfo(BrowserDetect.parseUserAgent(request));
//        user.setSecurity(new SecurityExpressionRoot(auth) {
//        });
//
//        // 用户过期验证
//        if (!getOverdueLoginExtraValidate().validate(user, request, response))
//        {
//            forwordLogin(request, response, user);
//            return;
//        }
//
//        // 额外用户登录验证
//        for (LoginExtraValidate v : getLoginExtraValidates())
//        {
//            if (!v.validate(user, request, response))
//            {
//                forwordLogin(request, response, user);
//                return;
//            }
//        }
//
//        // 登录日志
//        if (userLogManager != null)
//        {
//            UserLog userLog = new UserLog(0, user.getIp(), user.getClientInfo(), user.getUsername(), SecurityConstant.LOGIN_LOG_LOGINED, new Timestamp(System.currentTimeMillis()),
//                    SecurityConstant.LOG_TYPE_LOGIN);
//            userLogManager.add(userLog);
//        }
//
//        HttpSession session = request.getSession();
//        session.setAttribute(SecurityConstant.LOGIN_USER, user);
//        session.setAttribute(SecurityConstant.IS_LOGIN, Boolean.TRUE);
//        session.setAttribute(SecurityConstant.ROLES_CONSTANT, rolesConstantField);
//
//        final Object result = redirectUrl(request, response);
//        if (result == Boolean.FALSE)
//        {
//            String loginAfterEnterAddress = user.getExtendInfo().getString(SecurityConstant.LOGIN_AFTER_ENTER_ADDRESS);
//            if (StringUtils.isBlank(loginAfterEnterAddress) || (session.getAttribute(SAVED_REQUEST) instanceof SavedRequest))
//            {
//                super.onAuthenticationSuccess(request, response, authentication);
//            }
//            else
//            {
//                response.sendRedirect(request.getContextPath() + loginAfterEnterAddress);
//            }
//        }
//        else if (result instanceof FilterChain)
//        {
//            HttpServletRequest requestSource = request;
//            if (request.getAttribute("requestSource") instanceof HttpServletRequest)
//            {
//                requestSource = (HttpServletRequest) request.getAttribute("requestSource");
//            }
//
//            FilterChain chain = (FilterChain) result;
//            chain.doFilter(requestSource, response);
//        }
//
//    }
//
//    private void forwordLogin(HttpServletRequest request, HttpServletResponse response, User user) throws ServletException, IOException
//    {
//        HttpSession session = request.getSession();
//        String message=String.valueOf(session.getAttribute(SecurityConstant.LOGIN_LOG_OFFLIED_CUSTOM_MESSAGE_KEY));
//        
//        if (StringUtils.isNotBlank(message))
//        {
//            if (session.getAttribute(SecurityConstant.USER_NOT_START_USE) == Boolean.TRUE)
//            {
//                message = SecurityConstant.LOGIN_LOG_USER_NOT_START_USE;
//            }
//            else if (session.getAttribute(SecurityConstant.USER_IS_END_USE) == Boolean.TRUE)
//            {
//                message = SecurityConstant.LOGIN_LOG_USER_IS_END_USE;
//            }
//            else
//            {
//                message = SecurityConstant.LOGIN_LOG_OFFLIED_BY_EXTRA_VALIDATE;
//            }
//        }
//        
//        sessionRegistry.offline(message, new String[] { user.getUsername() });
//        request.setAttribute(SecurityConstant.FORWORD_LOGIN, Boolean.TRUE);
//        RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
//        dispatcher.forward(request, response);
//    }
//
//    private Object redirectUrl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
//    {
//        String redirectUrl = StringUtils.trim(request.getParameter("redirectUrl"));
//        if (StringUtils.isNotEmpty(redirectUrl) && redirectUrl.startsWith(request.getContextPath()))
//        {
//            if (request.getAttribute("filterChain") instanceof FilterChain)
//            {
//                return request.getAttribute("filterChain");
//            }
//            else
//            {
//                response.sendRedirect(redirectUrl);
//            }
//            return Boolean.TRUE;
//        }
//
//        return Boolean.FALSE;
//    }
//
//    public void setLoginExtraValidates(List<LoginExtraValidate> loginExtraValidates)
//    {
//        this.loginExtraValidates = loginExtraValidates;
//    }
//
//    public List<LoginExtraValidate> getLoginExtraValidates()
//    {
//        return loginExtraValidates;
//    }
//
//    public LoginExtraValidate getOverdueLoginExtraValidate()
//    {
//        return overdueLoginExtraValidate;
//    }
//
//    public void setOverdueLoginExtraValidate(LoginExtraValidate overdueLoginExtraValidate)
//    {
//        this.overdueLoginExtraValidate = overdueLoginExtraValidate;
//    }
//
//    @Override
//    public void afterPropertiesSet() throws Exception
//    {
//        if (loginExtraValidates == null)
//        {
//            if (context == null)
//            {
//                loginExtraValidates = Collections.emptyList();
//            }
//            else
//            {
//                Map<String, LoginExtraValidate> beans = context.getBeansOfType(LoginExtraValidate.class);
//                loginExtraValidates = Collections.unmodifiableList(new ArrayList<LoginExtraValidate>(beans.values()));
//            }
//        }
//
//        rolesConstantField = new FieldMethodizer(rolesConstant.getClass().getName());
//    }
}
